from __future__ import absolute_import
from pkgr.repo import RepoGeneric
from pkgr.util import calc_cookie_file
import solv

import os
import rpm
import logging
logger = logging.getLogger('pkgr.repos.System')

class RepoSystem(RepoGeneric):
    def add_too_pool(self, pool):
        repo = pool.add_repo(self.name)
        repo.appdata = self
        
        
        
        # notify the pool of the installed repo
        pool.installed = repo
        
        
        systemroot = self.get_root_dir()
        
        root = self.join_root_dir('var','lib','rpm','Packages')
        
        rootdir =  self.join_root_dir('var','lib','rpm')
        
        if not os.path.exists(rootdir):
            os.makedirs(rootdir)
            #rpm.addMacro("_dbpath", rootdir)
            logger.debug('Initializing rpm db at %s %s %s', systemroot,rootdir, root)
            ts = rpm.TransactionSet(self.get_root_dir())
            ts.initDB()
            #rpm.rebuilddb(systemroot)
            #rpm.delMacro("_dbpath")
            
         
        assert os.path.exists(root), "Packages does not exist %s" % root
            
        logger.debug('Using root %s', self.get_root_dir())
        # TODO: handle caching
        
        self.set_libsolv_repo(repo)
        
        
        #self.get_libsolv_repo().add_rpmdb_root(None, self.get_root_dir(), solv.Repo.REPO_REUSE_REPODATA)
        logger.debug('Writing system repo cache...')
        
        
        #f = solv.xfopen(self.cachepath())
        #repo.add_rpmdb_reffp(f, solv.Repo.REPO_REUSE_REPODATA)
        repo.add_rpmdb(solv.Repo.REPO_REUSE_REPODATA|solv.Repo.REPO_USE_ROOTDIR)
        #self.writecachedrepo(None)
        return True
